package cn.com.se.sharepictrue.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.adapter.ShareListAdapter;
import cn.com.se.sharepictrue.bean.ConcernAndFans;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.ImageLoader;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.quickadapter.BaseAdapterHelper;
import cn.com.se.sharepictrue.utils.StringUtils;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cn.com.se.sharepictrue.widget.LoadMoreListener;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 个人主页界面
 * Created by KIDNG on 2015/11/2.
 */
public class PersonalHomepageActivity extends Activity implements ShareListAdapter.ShareItemStatusListener, SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.lv_personal_list)
    ListView mLvPersonalList;
    @Bind(R.id.tv_personal_name_top)
    TextView mTvlNameTop;
    @Bind(R.id.rl_personal_top)
    RelativeLayout mRlPersonalTop;
    @Bind(R.id.srl_mine_homepage_refresh)
    SwipeRefreshLayout mSrlMineCollectionRefresh;
    TextView mTvFollowing;
    TextView mTvFollower;
    private View mHeader;
    private List<HomeShareBean> beans;
    private int headerHeight = 0;
    private int backHeight = 0;
    public static String HOMEPAGE_USERID = "userid";
    public static String HOMEPAGE_USERNAME = "username";
    public static String HOMEPGE_USERPIC = "userpic";
    public static String HOMEPAGE_KEY = "key";
    public static String HOMEPAGE_ME = "me";
    public static String HOMEPAGE_OTHER = "other";
    private final static int REQUEST_CODE_SHARE = 4;
    private boolean isMineHomepage;


    private String mUserId;
    private int nowPage = 1;
    private int defaultPageSize = 20;
    private String mUserPic;
    private String mUserName;

    private ShareListAdapter mShareListAdapter;

    private final int mLoadInLastRow = 4;
    private boolean hasMore = true;
    private boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_homepage);
        ButterKnife.bind(this);
        initWhatHomepage();
        initHeader();
        initTopLayout();
        initConcernAndFans();
        initRefreshView();

    }

    private void initTopLayout() {
        if (!StringUtils.isEmpty(mUserName))
            mTvlNameTop.setText(mUserName);
        else
            mTvlNameTop.setText("个人主页");
    }

    private void initRefreshView() {
        mSrlMineCollectionRefresh.setOnRefreshListener(this);
        mSrlMineCollectionRefresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mSrlMineCollectionRefresh.post(new Runnable() {
            @Override
            public void run() {
                mSrlMineCollectionRefresh.setRefreshing(true);
                initList();
            }
        });
    }

    private void initWhatHomepage() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String str = null;
        if (bundle != null) {
            str = bundle.getString(HOMEPAGE_KEY);
            mUserId = bundle.getString(HOMEPAGE_USERID);
            mUserName = bundle.getString(HOMEPAGE_USERNAME);
            mUserPic = bundle.getString(HOMEPGE_USERPIC);
            //selectedShareData = (HomeShareBean) bundle.getSerializable(HOMEPAGE_SHAREINFO);
            // mUserId = selectedShareData.getUserId();
        }
        // String str = intent.getStringExtra(HOMEPAGE_KEY);
        if (str != null && str.equals(HOMEPAGE_ME)) isMineHomepage = true;
        else isMineHomepage = false;
    }

    private void initConcernAndFans() {

        ShareApi.getUserConcernAndFans(PersonalHomepageActivity.this, mUserId, new CallBack<NetworkResponse<ConcernAndFans>>() {
            @Override
            public void onFail() {

            }

            @Override
            public void onResponse(NetworkResponse<ConcernAndFans> response) {
                if (!response.isStatus())
                    ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                else {
                    ConcernAndFans c = response.getData();
                    mTvFollowing.append(" " + c.getMyConcernCount());
                    mTvFollower.append(" " + c.getMyFansCount());
                }
            }
        });
    }

    private void initList() {
        nowPage = 1;
        ShareApi.herShare(PersonalHomepageActivity.this, mUserId, nowPage, defaultPageSize, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
            @Override
            public void onStart() {
                super.onStart();
                mSrlMineCollectionRefresh.setRefreshing(true);
            }

            @Override
            public void onFail() {
                mSrlMineCollectionRefresh.setRefreshing(false);
                ToastUtils.show(PersonalHomepageActivity.this, "加载失败");
            }

            @Override
            public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                mSrlMineCollectionRefresh.setRefreshing(false);
                if (!response.isStatus())
                    ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                else {
                    beans = response.getData();
                    initListData();
                }
            }
        });
    }

    public void loadMoreShare() {
        nowPage++;
        ShareApi.herShare(PersonalHomepageActivity.this, mUserId, nowPage, defaultPageSize, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
            @Override
            public void onFail() {
                isLoading = false;
                ToastUtils.show(PersonalHomepageActivity.this, "加载失败..");
            }

            @Override
            public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                isLoading = false;
                if (!response.isStatus()) {//加载失败
                    ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                } else {
                    addToList(response.getData());
                }
                if (response.getHasMore() != null && response.getHasMore().equals("0")) {
                    hasMore = false;
                }
                if (response.getHasMore() == null) hasMore = false;
            }
        });
    }

    private void addToList(List<HomeShareBean> data) {
        if (data != null) {
            mShareListAdapter.addAll(data);
            mShareListAdapter.notifyDataSetChanged();
        }
    }

    private void initListData() {
        if (beans != null && beans.size() > 0) {
            mShareListAdapter = new ShareListAdapter(PersonalHomepageActivity.this, R.layout.item_share_list, beans);
            mShareListAdapter.setShareItemStatusListener(this);
            mLvPersonalList.setAdapter(mShareListAdapter);
            mLvPersonalList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position - 1 < 0)
                        return;
                    Intent intent = new Intent(PersonalHomepageActivity.this, ShareDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("key", mShareListAdapter.getItem(position - 1));
                    intent.putExtra("item", bundle);
                    intent.putExtra("position", position - 1);
                    startActivityForResult(intent, REQUEST_CODE_SHARE);
                }
            });
           mLvPersonalList.post(new Runnable() {
               @Override
               public void run() {
                   if(mLvPersonalList!=null){
                       mLvPersonalList.setOnScrollListener(new AbsListView.OnScrollListener() {
                           @Override
                           public void onScrollStateChanged(AbsListView view, int scrollState) {

                           }

                           @Override
                           public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                               if (firstVisibleItem == 0) {
                                   if (backHeight >= (headerHeight + mHeader.getTop())) {
                                       if (mRlPersonalTop.getVisibility() == View.GONE)
                                           mRlPersonalTop.setVisibility(View.VISIBLE);
                                   } else {
                                       if (mRlPersonalTop.getVisibility() == View.VISIBLE)
                                           mRlPersonalTop.setVisibility(View.GONE);
                                   }
                               } else {
                                   mRlPersonalTop.setVisibility(View.VISIBLE);
                               }
                               if (hasMore && !isLoading) {
                                   int lastVisibleItem = firstVisibleItem + visibleItemCount;
                                   if (lastVisibleItem >= totalItemCount - mLoadInLastRow) {
                                       isLoading = true;
                                       loadMoreShare();
                                   }
                               }

                           }
                       });
                   }
               }
           });
        }
    }



    private void initHeader() {
        mHeader = getLayoutInflater().inflate(R.layout.header_personal_homepage, null);
        mHeader.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (headerHeight == 0) {
                    headerHeight = mHeader.getHeight();
                }
            }
        });
        mLvPersonalList.addHeaderView(mHeader);
        CircleImageView civ = (CircleImageView) mHeader.findViewById(R.id.iv_personal_avatar);
        if (mUserPic != null && mUserPic.length() > 0)
            ImageLoader.getInstance(PersonalHomepageActivity.this).load(civ, mUserPic);
        if (isMineHomepage) {
            civ.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(PersonalHomepageActivity.this, MineInfoActivity.class);
                    startActivity(intent);
                }
            });
        }
        TextView tv = (TextView) mHeader.findViewById(R.id.tv_personal_name);
        tv.setText(mUserName);
        mTvFollowing = (TextView) mHeader.findViewById(R.id.tv_personal_following);
        mTvFollower = (TextView) mHeader.findViewById(R.id.tv_personal_follower);
    }

    @OnClick({R.id.iv_personal_back, R.id.iv_personal_back_top})
    public void back(View v) {
        finish();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            backHeight = mRlPersonalTop.getHeight();
        }
        super.onWindowFocusChanged(hasFocus);
    }


    @Override
    public void avatarClick(BaseAdapterHelper helper, HomeShareBean item) {

    }

    @Override
    public void concernClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String concernId = item.getConcernUserId();
        if (concernId == null) ToastUtils.show(PersonalHomepageActivity.this, "请登录");
        else
            ShareApi.concern(PersonalHomepageActivity.this, item.getUserId(),
                    concernId.equals(HomeShareBean.HOME_SHARE_NO_CONCERN),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(PersonalHomepageActivity.this, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                            else {
                                if (item.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
                                    item.setConcernUserId(item.getUserId());
                                else
                                    item.setConcernUserId(HomeShareBean.HOME_SHARE_NO_CONCERN);
                                mShareListAdapter.notifyDataSetChanged();
                            }

                        }
                    });

    }

    @Override
    public void praiseClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String likeIt = item.getPraiseStatus();
        if (likeIt == null) ToastUtils.show(PersonalHomepageActivity.this, "请登录");
        else
            ShareApi.praise(PersonalHomepageActivity.this,
                    item.getShareId(),
                    likeIt.equals(HomeShareBean.HOME_SHARE_NO_PRAISE),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(PersonalHomepageActivity.this, "点赞" + item.getUserName() + "失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus()) {
                                ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                            } else {
                                if (item.getPraiseStatus().equals(HomeShareBean.HOME_SHARE_NO_PRAISE)) {
                                    item.setPraiseStatus(HomeShareBean.HOME_SHARE_IS_PRAISE);
                                    item.setPraiseNum(item.getPraiseNum() + 1);
                                } else {
                                    item.setPraiseStatus(HomeShareBean.HOME_SHARE_NO_PRAISE);
                                    item.setPraiseNum(item.getPraiseNum() - 1);
                                }

                                mShareListAdapter.notifyDataSetChanged();
                            }
                        }
                    });
    }

    @Override
    public void collectionClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String favorite = item.getFavoriteStatus();
        if (favorite == null) ToastUtils.show(PersonalHomepageActivity.this, "请登录");
        else
            ShareApi.favorite(PersonalHomepageActivity.this,
                    item.getShareId(),
                    favorite.equals(HomeShareBean.HOME_SHARE_NO_FAVORITE),
                    new CallBack<NetworkResponse<String>>() {
                        @Override
                        public void onFail() {
                            ToastUtils.show(PersonalHomepageActivity.this, "操作失败");
                        }

                        @Override
                        public void onResponse(NetworkResponse<String> response) {
                            if (!response.isStatus())
                                ToastUtils.show(PersonalHomepageActivity.this, response.getError());
                            else {
                                if (item.getFavoriteStatus().equals(HomeShareBean.HOME_SHARE_NO_FAVORITE))
                                    item.setFavoriteStatus(HomeShareBean.HOME_SHARE_IS_FAVORITE);
                                else
                                    item.setFavoriteStatus(HomeShareBean.HOME_SHARE_NO_FAVORITE);
                                mShareListAdapter.notifyDataSetChanged();
                            }

                        }
                    });
    }

    @Override
    public void commentClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(PersonalHomepageActivity.this, ShareDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", item);
        intent.putExtra("item", bundle);
        intent.putExtra("position", helper.getPosition());
        startActivityForResult(intent, REQUEST_CODE_SHARE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HomeShareBean item = null;
        int position = -1;
        if (requestCode == REQUEST_CODE_SHARE && resultCode == Activity.RESULT_OK) {
            Log.d("xxxxxxxxxxxxxx", "return ok");
            if (data != null) {
                Bundle bundle = data.getBundleExtra("item");
                if (bundle != null)
                    item = (HomeShareBean) bundle.getSerializable("key");
                position = data.getIntExtra("position", -1);
            }
            if (item != null) Log.d("sssssss", item.toString());
            if (item != null && position != -1 && mShareListAdapter.getCount() > position) {
                mShareListAdapter.set(position, item);
            }
        }
    }


    @Override
    public void onRefresh() {
        initList();
    }
}
